const Koa = require('koa');
const router = require('koa-router')();
// const bodyParser = require('koa-bodyparser');
const views = require('koa-views');
const serve = require('koa-static');

class MyKoa extends Koa {

    constructor(views_path, static_path, extension = 'html') {
        super();

        this
            // .use(bodyParser())
            .use(views(views_path, // 配置模板引擎所在的目录z
                {
                    extension: extension, // 使用 HTML、EJS 等模板引擎
                }))
            .use(serve(static_path));// 配置静态文件目录
    }

    route(maps, method) {
        if (!Array.isArray(maps[0]))
            maps = [maps]
        for (let [url, callback] of maps)
            router[method](url, callback)
        return this
    }

    get(maps) {
        return this.route(maps, 'get')
    }

    post(maps) {
        return this.route(maps, 'post')
    }

    start(port = 3080) {
        this
            .use(router.routes())
            .listen(
                port,
                _ => console.log(`Server is running on http://localhost:${port}`));
    }
}

module.exports = MyKoa
